﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using System.Xml.Linq;
using Microsoft.WindowsAzure.ServiceRuntime;
using System.IO;
using Microsoft.CloudSaver.Web.Infrastructure;
using System.Net;

namespace Microsoft.CloudSaver.Web
{
    public partial class Choice : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var res = CloudUtils.GetValue(User.Identity.Name, "Area");
            if (res != null && res != "Undefined") Response.Redirect("~/Files.aspx");
        }

        protected void cmdITPro_Click(object sender, ImageClickEventArgs e)
        {
            CloudUtils.SetValue(User.Identity.Name, "Area", "ITPro");
            ThreadPool.QueueUserWorkItem(new WaitCallback(DownloadFrom), "http://risorse.blob.core.windows.net/itpro?restype=container&comp=list");
            Response.Redirect("~/Files.aspx");
        }

        protected void cmdDev_Click(object sender, ImageClickEventArgs e)
        {
            CloudUtils.SetValue(User.Identity.Name, "Area", "Dev");
            ThreadPool.QueueUserWorkItem(new WaitCallback(DownloadFrom), "http://risorse.blob.core.windows.net/dev?restype=container&comp=list");
            Response.Redirect("~/Files.aspx");
        }

        private void DownloadFrom(object url)
        {
            XDocument doc = XDocument.Load(url.ToString());
            LocalResource local = RoleEnvironment.GetLocalResource("TempStorage");
            var folder = new DirectoryInfo(Path.Combine(local.RootPath, "Downloads"));
            WebClient cl = new WebClient();
            if (!folder.Exists) folder.Create();
            doc.Descendants("Url").Select(p => new Uri(p.Value)).ToList().ForEach(p =>
            {
                var file=Path.Combine(folder.FullName, p.Name());
                if (!File.Exists(file)) cl.DownloadFile(p.AbsoluteUri, file);
                CloudUtils.SaveBlob(User.Identity.Name, "application/octet-stream", File.ReadAllBytes(file), p.Name());                
            });
        }
    }
}